﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Collections;

//http://varjabedian.net/archive/2008/04/22/binding-asp.net-treeview-to-a-dataset-or-an-objectdatasource.aspx

// http://stackoverflow.com/questions/606515/multiple-markers-on-a-google-map

namespace Mercator2
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        public const string CHILD_ID_FIELD_NAME = "DeviceID";
        public const string PAREN_ID_FIELD_NAME = "GroupID";
        public const string NODE_TEX_FIELD_NAME = "DeviceGroupName";
        public const string CHEC_TEX_FIELD_NAME = "Checked";

        public const string PAREN_TABLE_NAME = "DeviceGroup";
        public const string CHILD_TABLE_NAME = "Device";

        // Cria tabela de endereços para mostrar na grid em tempo de execucao
        DataSet addressDS = new DataSet();
        DataSet dsDevices = null;

        ArrayList sessionTreeView=null;
                
        DataSet treeviewDataSet = new DataSet();

        protected void Page_Load(object sender, EventArgs e)
        {
            TreeView1.ShowCheckBoxes = TreeNodeTypes.Leaf;

            if (!IsPostBack)
            {

                DataSet dsGroups = getData(WebConfig.GetDBConn(), PAREN_TABLE_NAME, "");

                treeviewDataSet.Tables.Add(dsGroups.Tables[0].TableName);
                treeviewDataSet.Tables[0].Columns.Add(CHILD_ID_FIELD_NAME, typeof(string));
                treeviewDataSet.Tables[0].Columns.Add(PAREN_ID_FIELD_NAME, typeof(string));
                treeviewDataSet.Tables[0].Columns.Add(NODE_TEX_FIELD_NAME, typeof(string));

                treeviewDataSet.Tables[0].Columns.Add(CHEC_TEX_FIELD_NAME, typeof(string));

                foreach (DataColumn columnItem in dsGroups.Tables[0].Columns)
                {
                    //treeviewDataSet.Tables[0].Columns.Add(columnItem.ColumnName, typeof(string));
                }

                DataRow treeviewRow = null;
                foreach (DataRow groupRow in dsGroups.Tables[0].Rows)
                {
                    treeviewRow = treeviewDataSet.Tables[0].NewRow();
                    treeviewRow[CHILD_ID_FIELD_NAME] = groupRow[PAREN_ID_FIELD_NAME];// "1112309";//"91234567890";//"1";//"9661112309";//"1";
                    treeviewRow[NODE_TEX_FIELD_NAME] = groupRow[NODE_TEX_FIELD_NAME]; // "Veículos Lifeware";

                    treeviewDataSet.Tables[0].Rows.Add(treeviewRow);
                }
                //DataRow treeviewRow = treeviewDataSet.Tables[0].NewRow();
                //treeviewRow[CHILD_ID_FIELD_NAME] = dsGroups.Tables[0].Rows[0][PAREN_ID_FIELD_NAME];// "1112309";//"91234567890";//"1";//"9661112309";//"1";
                //treeviewRow[NODE_TEX_FIELD_NAME] = dsGroups.Tables[0].Rows[0][NODE_TEX_FIELD_NAME]; // "Veículos Lifeware";

                //treeviewDataSet.Tables[0].Rows.Add(treeviewRow);

                dsDevices = getData(WebConfig.GetDBConn(), "Device", "");
                Session["dsDevices"] = dsDevices;

                foreach (DataRow childRow in dsDevices.Tables[0].Rows)
                {
                    treeviewRow = treeviewDataSet.Tables[0].NewRow();
                    treeviewRow[CHILD_ID_FIELD_NAME] = childRow[CHILD_ID_FIELD_NAME];
                    treeviewRow[PAREN_ID_FIELD_NAME] = childRow[PAREN_ID_FIELD_NAME];//"1112309";//"91234567890";//"1";//childRow[PAREN_ID_FIELD_NAME];// "1";
                    treeviewRow[NODE_TEX_FIELD_NAME] = childRow["VRN"]; // placa
                    treeviewDataSet.Tables[0].Rows.Add(treeviewRow);
                }

                // The two extra parameters that you have to pass to the constructor of HierarchicalDataSet are two column names. 
                // The first one being the primary key of the table, and the second one being the parent key which usually would be a 
                // foreign key to the primary key of the same table; this allows modeling the tree structure in a database table. Here is a simple design of such a table.
                // You can use this:
                //TreeView1.DataSource = new HierarchicalDataSet(dataSet, "ID", "ParentID");
                TreeView1.DataSource = new HierarchicalDataSet(treeviewDataSet, CHILD_ID_FIELD_NAME, PAREN_ID_FIELD_NAME);

                // OR you can use the extensions for TreeView if you are using .NET 3.5
                //TreeView1.SetDataSourceFromDataSet(dataSet, "ID", "ParentID");

                // OR This line, will load the tree starting from the parent record of value = 1
                //TreeView1.DataSource = new HierarchicalDataSet(dataSet, "ID", "ParentID", 1);

                TreeView1.DataBindings[0].ValueField = CHILD_ID_FIELD_NAME;
                TreeView1.DataBindings[0].TextField = NODE_TEX_FIELD_NAME;

                TreeView1.DataBind();

                showMap();

                addressDS.Tables.Add("Address");
                addressDS.Tables[0].Columns.Add("Endereço", typeof(string));
                addressDS.Tables[0].Columns.Add("País", typeof(string));
                addressDS.Tables[0].Columns.Add("Estado", typeof(string));
                addressDS.Tables[0].Columns.Add("Cidade", typeof(string));
                addressDS.Tables[0].Columns.Add("Bairro", typeof(string));
                addressDS.Tables[0].Columns.Add("Latitude", typeof(string));
                addressDS.Tables[0].Columns.Add("Longitude", typeof(string));
                addressDS.Tables[0].Columns.Add("Data/hora", typeof(string));
                addressDS.Tables[0].Columns.Add("Placa", typeof(string));
                addressDS.Tables[0].Columns.Add("Qtd. bytes", typeof(string));
                addressDS.Tables[0].Columns.Add("Veloc. bytes/seg", typeof(string));
                addressDS.Tables[0].Columns.Add("Unit ID", typeof(string));

                addressGrid.DataSource = addressDS;
                addressGrid.DataBind();

                Session["addressDS"] = addressDS;

                if (Session["sessionTreeView"] != null)
                {
                    sessionTreeView = (ArrayList)Session["sessionTreeView"];
                    for (int i = 0; i < sessionTreeView.Count; i++)
                    {
                        TreeNode selectedNode = (TreeNode)sessionTreeView[i];
                        string VRN = selectedNode.Text;

                        updateCheckedNodes(VRN, TreeView1.Nodes);
                    }
                }
                else
                {
                    sessionTreeView = new ArrayList();
                    Session["sessionTreeView"] = sessionTreeView;
                }
            }
        }

        public System.Data.DataSet getData(string connectionString, string currentTableName, string whereClause)
        {
            System.Data.DataSet tempDataSet = new System.Data.DataSet();
            SqlDataAdapter currentDataAdapter = null;

            try
            {
                SqlConnection dataConnection = new SqlConnection(connectionString);

                //OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder();//(OleDbDataAdapter)currentDataAdapter);
                //cmdBuilder.GetInsertCommand();

                string SQL = "SELECT * FROM " + currentTableName;
                if ((whereClause != null) && (whereClause.Trim() != ""))
                    SQL += " WHERE " + whereClause;

                SqlCommand tableCommand = new SqlCommand(SQL, dataConnection);

                currentDataAdapter = new SqlDataAdapter(tableCommand);

                currentDataAdapter.Fill(tempDataSet);
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now + " - Erro : " + ex.Message + "\nStackTrace:" + ex.StackTrace);
                //throw;
            }

            return tempDataSet;
        }

        public System.Data.DataSet getDataSQL(string connectionString, string currentTableName, string SQL)
        {
            System.Data.DataSet tempDataSet = new System.Data.DataSet();
            SqlDataAdapter currentDataAdapter = null;

            try
            {
                SqlConnection dataConnection = new SqlConnection(connectionString);

                //OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder();//(OleDbDataAdapter)currentDataAdapter);
                //cmdBuilder.GetInsertCommand();

                //string SQL = "SELECT * FROM " + currentTableName;
                //if ((whereClause != null) && (whereClause.Trim() != ""))
                //    SQL += " WHERE " + whereClause;

                SqlCommand tableCommand = new SqlCommand(SQL, dataConnection);

                currentDataAdapter = new SqlDataAdapter(tableCommand);

                currentDataAdapter.Fill(tempDataSet);
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now + " - Erro : " + ex.Message + "\nStackTrace:" + ex.StackTrace);
                //throw;
            }

            return tempDataSet;
        }

        public void showMap()
        {
            try
            {
                string latitudeStr = "";
                string longitudeStr = "";
                string markerTitle = "";

                // Coloca mapa e alfinete na pagina com posicionamento do servidor.

                if ((Request.QueryString != null) && (Request.QueryString.Count > 0))
                {
                    latitudeStr = Request.QueryString["latitude"].ToString();
                    longitudeStr = Request.QueryString["longitude"].ToString();
                    if(Request.QueryString.Count>=3)
                        markerTitle=Request.QueryString[2].ToString();

                    //AddPointToMap(latitudeStr, longitudeStr, markerTitle);
                }
                else
                {
                    //-40,288615	-20,3558483333333
                    latitudeStr = "-20.3558483333333";// Request.QueryString["latitude"].ToString();
                    longitudeStr = "-40.288615";// Request.QueryString["longitude"].ToString();
                    //AddPointToMap(latitudeStr, longitudeStr,);
                    markerTitle = "Latitude=" + latitudeStr + " - Longitude=" + longitudeStr;
                }

                AddPointToMap(latitudeStr, longitudeStr, markerTitle);
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now + " - Erro : " + ex.Message + "\nStackTrace:" + ex.StackTrace);
                //throw;
            }
        }

        private string AddPointToMap(string Latitude, string Longitude, string markerTitle)
        {
            String Locations = "";

            Latitude = Latitude.Replace(",", ".");
            Longitude = Longitude.Replace(",", ".");

            // create a line of JavaScript for marker on map for this record
            //http://stackoverflow.com/questions/606515/multiple-markers-on-a-google-map
            Locations = Environment.NewLine + " map.addOverlay(new GMarker(new GLatLng(" + Latitude + "," + Longitude + 
                "), {title: '" +
                 markerTitle + "',  icon:new GIcon(G_DEFAULT_ICON, 'FireTruck.png')}));";
                //markerTitle + "', clickable: false, icon:new GIcon('~/truck.png')}));";

            // construct the final script
            //alert(window.location.host);
            js.Text = @"<script type='text/javascript'>
                            function initialize() {
                              if (GBrowserIsCompatible()) {

                                var map = new GMap2(document.getElementById('map_canvas'));
                                map.setCenter(new GLatLng(" + Latitude + "," + Longitude + @"),15); 
                                " + Locations + @"
                                map.setUIToDefault();
                              }
                            }
                            </script> ";

            setTextAddress(Longitude, Latitude);

            //setGridAddress(Longitude, Latitude);

            return Locations;
        }

        private void AddPointTableToMap(DataTable pointTable)
        {
            String Locations = "";
            string Latitude = "";
            string Longitude = "";

            foreach (DataRow pointRow in pointTable.Rows)
            {
                Latitude = pointRow["Latitude"].ToString();
                Longitude = pointRow["Longitude"].ToString(); 
                Latitude = Latitude.Replace(",", ".");
                Longitude = Longitude.Replace(",", ".");

                setTextAddress(Longitude, Latitude);

                string markerTitle = "Latitude = " + Latitude + " - Longitude = " + Longitude;

                // create a line of JavaScript for marker on map for this record	
                //Locations += Environment.NewLine + " map.addOverlay(new GMarker(new GLatLng(" + Latitude + "," + Longitude + ")));";
                // create a line of JavaScript for marker on map for this record
                //http://stackoverflow.com/questions/606515/multiple-markers-on-a-google-map
                Locations = Environment.NewLine + " map.addOverlay(new GMarker(new GLatLng(" + Latitude + "," + Longitude +
                     markerTitle + "',  icon:new GIcon(G_DEFAULT_ICON,'RedCar.png') }));";
                    //markerTitle + "', clickable: false, icon:new GIcon('~/truck.png')}));";
            }

            // construct the final script
            //alert(window.location.host);
            js.Text = @"<script type='text/javascript'>
                            function initialize() {
                              if (GBrowserIsCompatible()) {

                                var map = new GMap2(document.getElementById('map_canvas'));
                                map.setCenter(new GLatLng(" + Latitude + "," + Longitude + @"),15); 
                                " + Locations + @"
                                map.setUIToDefault();
                              }
                            }
                            </script> ";

        }

        private string AddPointsToMap(String Locations)
        {
            return AddPointsToMapWithCenter(Locations, "", "");
        }

        private string AddPointsToMapWithCenter(String Locations, string CenterMapLatitude, string CenterMapLongitude)
        {
            // -40.288124	-20.355536	0.0	0.0	R. Natal, 1-61 - Praia de Itapoã, Vila Velha - ES, 29101-710, Brazil
            if ((CenterMapLatitude == null) || (CenterMapLatitude.Trim() == ""))
                CenterMapLatitude = "-20.355536";

            if ((CenterMapLongitude == null) || (CenterMapLongitude.Trim() == ""))
                CenterMapLongitude = "-40.288124";

            CenterMapLongitude = CenterMapLongitude.Replace(",", ".");
            CenterMapLatitude = CenterMapLatitude.Replace(",", ".");

            // construct the final script
            //alert(window.location.host);
            js.Text = @"<script type='text/javascript'>
                            function initialize() {
                              if (GBrowserIsCompatible()) {

                                var map = new GMap2(document.getElementById('map_canvas'));
                                map.setCenter(new GLatLng(" + CenterMapLatitude + "," + CenterMapLongitude + @"),13); 
                                " + Locations + @"
                                map.setUIToDefault();
                              }
                            }
                            </script> ";

            //setTextAddress(Longitude, Latitude);

            return Locations;
        }

        private void setTextAddress(string longitude, string latitude)
        {

            // http://stackoverflow.com/questions/3151450/google-geolocation-api-use-longitude-and-latitude-to-get-address

            // 	-40.402864	-20.342288	0.0	0.0	BR-262 - Pistal Lateral - Vila Capixaba, Cariacica - ES, Brazil
            // -40.288124	-20.355536	0.0	0.0	R. Natal, 1-61 - Praia de Itapoã, Vila Velha - ES, 29101-710, Brazil
            // http://code.google.com/apis/maps/documentation/geocoding/#ReverseGeocoding
            //http://maps.google.com/maps/api/geocode/xml?latlng=40.714224,-73.961452&sensor=false

            try
            {
                longitude = longitude.Replace(",", ".");
                latitude = latitude.Replace(",", ".");

                //string longitude = "40.714224"; string latitude = "-73.961452";
                //string longitude = "-40.288124"; string latitude = "-20.355536";
                string Address_ShortName = "";
                string Address_country = "";
                string Address_administrative_area_level_1 = "";
                string Address_administrative_area_level_2 = "";
                string Address_administrative_area_level_3 = "";
                string Address_colloquial_area = "";
                string Address_locality = "";
                string Address_sublocality = "";
                string Address_neighborhood = "";
                string Street_address = "";

                ReverseGeoLookup.ReverseGeoLookup.ReverseGeoLoc(longitude, latitude,
                    out Address_ShortName,
                    out Address_country,
                    out Address_administrative_area_level_1,
                    out Address_administrative_area_level_2,
                    out Address_administrative_area_level_3,
                    out Address_colloquial_area,
                    out Address_locality,
                    out Address_sublocality,
                    out Address_neighborhood,
                    out Street_address);

                txtAddress.Text =
                    "Street_address=" + Street_address + "\n" +
                    "Address_ShortName=" + Address_ShortName + "\n" +
                    "Address_country=" + Address_country + "\n" +
                    "Address_administrative_area_level_1=" + Address_administrative_area_level_1 + "\n" +
                    "Address_administrative_area_level_2=" + Address_administrative_area_level_2 + "\n" +
                    "Address_administrative_area_level_3=" + Address_administrative_area_level_3 + "\n" +
                    "Address_colloquial_area=" + Address_colloquial_area + " -  " +
                    "Address_locality=" + Address_locality + "\n" +
                    "Address_sublocality=" + Address_sublocality + "\n" +
                    "Address_neighborhood=" + Address_neighborhood;

                //Console.In.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now + " - Erro : " + ex.Message + "\nStackTrace:" + ex.StackTrace);
                //throw;
            }
        }

        protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
        {
            showNodeInMap();
        }

        // http://forums.asp.net/t/643832.aspx/1?Getting+TreeView+to+postback+when+node+is+checked+unchecked
        // Re: Getting TreeView to postback when node is checked/unchecked

        //Jul 23, 2004 08:46 PM | LINK
        //This works!! Thanks!!! I'm writing a control that inherits from TreeView. 
        // I can set the "onclick" attribute of the control to the name of a javascript 
        // function that I render like this: Attributes["onclick"] = "javascript:postbackOnCheck(event)"; 
        // My javascript function reads like this for netscape interoperability: function postbackOnCheck(e) 
        //{ var isNav = (window.navigator.appName.toLowerCase().indexOf("netscape")>=0); var o; if (isNav && e != null) o = e.target; 
        // else o = window.event.srcElement; if (o.tagName == 'INPUT' && o.type == 'checkbox' && o.name != null && o.name.indexOf('CheckBox') > -1) __doPostBack("",""); } 

        protected void TreeView1_SelectedNodeChanged1(object sender, TreeNodeEventArgs e)
        {
            TreeNode selectedNode = (TreeNode)e.Node;

            if (!selectedNode.Checked)
                if (selectedNode.Parent != null)
                    selectedNode.Parent.Checked = false;

            foreach (TreeNode childNode in selectedNode.ChildNodes)
            {
                if (selectedNode.Checked)
                    childNode.Checked = true;
                else
                    childNode.Checked = false;

            }

            showNodeInMap();

            sessionTreeView = new ArrayList();
            setSessionCheckedNodes(TreeView1.Nodes);
            Session["sessionTreeView"] = sessionTreeView;
        }

        private void setSessionCheckedNodes(TreeNodeCollection treeNodeCollection)
        {
            try
            {
                foreach (TreeNode nodeItem in treeNodeCollection)
                {
                    if (nodeItem.Checked)
                        sessionTreeView.Add(nodeItem);
                    else
                        sessionTreeView.Remove(nodeItem);

                    if (nodeItem.ChildNodes.Count > 0)
                        setSessionCheckedNodes(nodeItem.ChildNodes);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now + " - Erro : " + ex.Message + "\nStackTrace:" + ex.StackTrace);
                //throw;
            }
        }

        public void showNodeInMap()
        {

            try
            {
                String Locations = "";

                //clearOverlays() 	None 	Removes all overlays from the map, and fires the clearoverlays event.
                Locations = "map.clearOverlays();";
                AddPointsToMap(Locations);

                // limpa grid de endereços
                addressDS = (DataSet)Session["addressDS"];
                addressDS.Clear();
                addressGrid.DataSource = addressDS;
                addressGrid.DataBind();

                DataSet treeviewDataSet = new DataSet();

                DataSet dsGroups = null;
                //if (TreeView1.SelectedNode != null)
                if ((TreeView1.CheckedNodes.Count == 0) && (TreeView1.SelectedNode != null))
                {
                    dsGroups = getData(WebConfig.GetDBConn(), CHILD_TABLE_NAME, " VRN='" + TreeView1.SelectedNode.Text + "'");

                    if ((dsGroups != null) && (dsGroups.Tables.Count > 0))
                    {
                        DataTable dtDevice = dsGroups.Tables[0];
                        string latitudeStr = dtDevice.Rows[0]["LastLatitude"].ToString();
                        string longitudeStr = dtDevice.Rows[0]["LastLongitude"].ToString();

                        string deviceID = dtDevice.Rows[0]["DeviceID"].ToString();
                        string VRN = dtDevice.Rows[0]["VRN"].ToString();

                        string dataHora = dtDevice.Rows[0]["LastUploadtime"].ToString();

                        string markerTitle = "Placa: " + VRN + 
                            " - Dispositivo nr.: " + deviceID + 
                            " - Latitude=" + latitudeStr + " - Longitude=" + longitudeStr;

                        AddPointToMap(latitudeStr, longitudeStr, markerTitle);

                        DateTime lastUploadTime;
                        int seconds=1;
                        if (DateTime.TryParse(dataHora, out lastUploadTime))
                        {
                            DateTime currentTime = DateTime.Now;
                            seconds = currentTime.Subtract(lastUploadTime).Seconds;
                        }

                        int accumulatedBytesQty = 0;
                        int.TryParse(dtDevice.Rows[0]["TotalBytesReceivedMonth"].ToString(), out accumulatedBytesQty);

                        setGridAddress(longitudeStr, latitudeStr, VRN, dataHora, deviceID, seconds, accumulatedBytesQty);
                    }
                }
                else
                {
                    // -20,355095	-40,288451666666
                    string latitudeStr = "-20.355095";
                    string longitudeStr = "-40.288451666666";

                    foreach (TreeNode checkedNode in TreeView1.CheckedNodes)
                    //foreach (TreeNode deviceNode in TreeView1.Nodes)
                    {
                        dsGroups = getData(WebConfig.GetDBConn(), CHILD_TABLE_NAME, " VRN='" + checkedNode.Text + "'");
                        //dsGroups = getData(WebConfig.GetDBConn(), CHILD_TABLE_NAME, " VRN='" + deviceNode.Text + "'");

                        if ((dsGroups != null) && (dsGroups.Tables.Count > 0))
                        {
                            DataTable dtDevice = dsGroups.Tables[0];
                            if ((dtDevice != null) && (dtDevice.Rows.Count > 0))
                            {
                                latitudeStr = dtDevice.Rows[0]["LastLatitude"].ToString();
                                longitudeStr = dtDevice.Rows[0]["LastLongitude"].ToString();

                                latitudeStr = latitudeStr.Replace(",", ".");
                                longitudeStr = longitudeStr.Replace(",", ".");

                                string markerTitle = "Device = " + dtDevice.Rows[0]["DeviceID"].ToString();
                                markerTitle += " - Placa="  + dtDevice.Rows[0]["VRN"].ToString();
                                markerTitle += " - Latitude=" + latitudeStr;
                                markerTitle += " - Longitude=" + longitudeStr;

                                // Each overlay implements the GOverlay interface. Overlays can be added to a map using the GMap2.addOverlay() method 
                                // and removed using the GMap2.removeOverlay() method. (Note that the info window is added by default to the map.)
                                // create a line of JavaScript for marker on map for this record
                                //Locations += Environment.NewLine + " map.addOverlay(new GMarker(new GLatLng(" + latitudeStr + "," + longitudeStr + ")));";
                                Locations += Environment.NewLine + " map.addOverlay(new GMarker(new GLatLng(" + latitudeStr + "," + longitudeStr + ")" +
                                    ", {title: '" +
                                     markerTitle + "', icon:new GIcon(G_DEFAULT_ICON, 'RedCar.png')}));";
                                     // markerTitle + "', clickable: false}));";
                                     //markerTitle + "', clickable: false, icon:new GIcon('~/truck.png')}));";

                                string VRN = dtDevice.Rows[0]["VRN"].ToString();
                                string dataHora = dtDevice.Rows[0]["LastUploadtime"].ToString();
                                string deviceID = dtDevice.Rows[0]["DeviceID"].ToString();
                                DateTime lastUploadTime;
                                int seconds = 1;

                                int accumulatedBytesQty = 0;
                                int.TryParse(dtDevice.Rows[0]["TotalBytesReceivedMonth"].ToString(), out accumulatedBytesQty);

                                if (DateTime.TryParse(dataHora, out lastUploadTime))
                                {
                                    DateTime currentTime = DateTime.Now;
                                    seconds = currentTime.Subtract(lastUploadTime).Seconds;
                                }

                                setGridAddress(longitudeStr, latitudeStr, VRN, dataHora, deviceID, seconds, accumulatedBytesQty);
                            }
                        }
                    }                        
                    AddPointsToMapWithCenter(Locations, latitudeStr,longitudeStr);

                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now + " - Erro : " + ex.Message + "\nStackTrace:" + ex.StackTrace);
                //throw;
            }
        }

        private void setGridAddress(string longitude, string latitude, string VRN, string dataHora, string deviceID, double seconds, int AccumulatedBytesQty)
        {

            // http://stackoverflow.com/questions/3151450/google-geolocation-api-use-longitude-and-latitude-to-get-address

            // 	-40.402864	-20.342288	0.0	0.0	BR-262 - Pistal Lateral - Vila Capixaba, Cariacica - ES, Brazil
            // -40.288124	-20.355536	0.0	0.0	R. Natal, 1-61 - Praia de Itapoã, Vila Velha - ES, 29101-710, Brazil
            // http://code.google.com/apis/maps/documentation/geocoding/#ReverseGeocoding
            //http://maps.google.com/maps/api/geocode/xml?latlng=40.714224,-73.961452&sensor=false

            try
            {
                longitude = longitude.Replace(",", ".");
                latitude = latitude.Replace(",", ".");

                //string longitude = "40.714224"; string latitude = "-73.961452";
                //string longitude = "-40.288124"; string latitude = "-20.355536";
                string Address_ShortName = "";
                string Address_country = "";
                string Address_administrative_area_level_1 = "";
                string Address_administrative_area_level_2 = "";
                string Address_administrative_area_level_3 = "";
                string Address_colloquial_area = "";
                string Address_locality = "";
                string Address_sublocality = "";
                string Address_neighborhood = "";
                string Street_address = "";

                //<GeocodeResponse>
                //<status>OVER_QUERY_LIMIT</status>
                //</GeocodeResponse>
                ReverseGeoLookup.ReverseGeoLookup.ReverseGeoLoc(longitude, latitude,
                    out Address_ShortName,
                    out Address_country,
                    out Address_administrative_area_level_1,
                    out Address_administrative_area_level_2,
                    out Address_administrative_area_level_3,
                    out Address_colloquial_area,
                    out Address_locality,
                    out Address_sublocality,
                    out Address_neighborhood,
                    out Street_address);

                txtAddress.Text =
                    "Street_address=" + Street_address + "\n" +
                    "Address_ShortName=" + Address_ShortName + "\n" +
                    "Address_country=" + Address_country + "\n" +
                    "Address_administrative_area_level_1=" + Address_administrative_area_level_1 + "\n" +
                    "Address_administrative_area_level_2=" + Address_administrative_area_level_2 + "\n" +
                    "Address_administrative_area_level_3=" + Address_administrative_area_level_3 + "\n" +
                    "Address_colloquial_area=" + Address_colloquial_area + " -  " +
                    "Address_locality=" + Address_locality + "\n" +
                    "Address_sublocality=" + Address_sublocality + "\n" +
                    "Address_neighborhood=" + Address_neighborhood;

                //DataRow addressRow = addressDS.Tables[0].NewRow();
                //row["ID"] = "1";
                //addressRow[CHILD_ID_FIELD_NAME] = "1";// "1112309";//"91234567890";//"1";//"9661112309";//"1";
                //addressRow[NODE_TEX_FIELD_NAME] = "Veículos Lifeware";
                //addressDS.Tables[0].Rows.Add(addressRow);
                if (Session["addressDS"] != null)
                {
                    //if(int.TryParse(dsDevices.Tables[0].rows)
                    string bytesQt = "0"; //getBytesQty(deviceID);
                    int bytesQtyInt=AccumulatedBytesQty;
                    bytesQt = AccumulatedBytesQty.ToString();

                    double byteRate = 0;
                    if (int.TryParse(bytesQt, out bytesQtyInt))
                        byteRate = bytesQtyInt / seconds;

                    addressDS.Tables[0].Rows.Add(Street_address, Address_country, 
                        Address_administrative_area_level_1, Address_locality, Address_sublocality,
                        latitude, longitude, dataHora, VRN, bytesQt, byteRate.ToString(), deviceID);
                    addressGrid.DataSource = addressDS;
                    addressGrid.DataBind();
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now + " - Erro : " + ex.Message + "\nStackTrace:" + ex.StackTrace);
                //throw;
            }
        }

        private string getBytesQty(string deviceID)
        {
            //SELECT        DeviceID, SUM(DATALENGTH(ReceivedBytes)) AS QtdBytes
            //FROM            RelayLog
            //GROUP BY DeviceID
            //HAVING        (DeviceID = '9661112309')

            string bytesQty = "";

            try
            {
                string SQL =
                   "SELECT        DeviceID, SUM(DATALENGTH(ReceivedBytes)) AS QtdBytes " +
                   " FROM            RelayLog " +
                   " GROUP BY DeviceID " +
                   " HAVING        (DeviceID = '" + deviceID + "') ";//"9661112309') ";

                DataTable dtBytesQty = getDataSQL(WebConfig.GetDBConn(), "RelayLog", SQL).Tables[0];

                if (dtBytesQty.Rows.Count > 0)
                    bytesQty = dtBytesQty.Rows[0]["QtdBytes"].ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now + " - Erro : " + ex.Message + "\nStackTrace:" + ex.StackTrace);
                //throw;
            }

            return bytesQty;
        }

        /// <summary>
        /// Add property values to view state with set;
        /// </summary>
        public ArrayList marrlDDLSelecaoParam
        {
            get
            {
                ArrayList arlSelecao;
                if (ViewState["DDLSelecaoParam"] == null)
                {
                    arlSelecao = new ArrayList();
                }
                else
                {
                    arlSelecao = (ArrayList)ViewState["DDLSelecaoParam"];
                }
                ViewState.Add("DDLSelecaoParam", arlSelecao);
                return arlSelecao;
            }
            set
            {
                ViewState.Add("DDLSelecaoParam", value);
            }
        }

        public void updateCheckedNodes(string VRN, TreeNodeCollection nodes)
        {
            foreach (TreeNode nodeItem in nodes)
            {
                if (nodeItem.Text == VRN)
                    nodeItem.Checked = true;

                if (nodeItem.ChildNodes.Count > 0)
                    updateCheckedNodes(VRN, nodeItem.ChildNodes);
            }

            showNodeInMap();
        }
    }
}



                //DataSet dataSet = new DataSet();

                //dataSet.Tables.Add("Table");
                ////dataSet.Tables[0].Columns.Add("ID", typeof(string));
                //dataSet.Tables[0].Columns.Add(CHILD_ID_FIELD_NAME, typeof(string));
                ////dataSet.Tables[0].Columns.Add("ParentID", typeof(string));
                //dataSet.Tables[0].Columns.Add(PAREN_ID_FIELD_NAME, typeof(string));
                //dataSet.Tables[0].Columns.Add(NODE_TEX_FIELD_NAME, typeof(string));

                //DataRow row = dataSet.Tables[0].NewRow();
                ////row["ID"] = "1";
                //row[CHILD_ID_FIELD_NAME] = "1";// "1112309";//"91234567890";//"1";//"9661112309";//"1";
                ////row["Text"] = "Parent 1";
                //row[NODE_TEX_FIELD_NAME] = "Veículos Lifeware";
                //dataSet.Tables[0].Rows.Add(row);

                ////row = dataSet.Tables[0].NewRow();
                ////row["ID"] = "2";
                ////row["Text"] = "Parent 2";
                ////dataSet.Tables[0].Rows.Add(row);

                ////row = dataSet.Tables[0].NewRow();
                ////row["ID"] = "3";
                ////row["ParentID"] = "1";
                ////row["Text"] = "Child 1";
                ////dataSet.Tables[0].Rows.Add(row);

                ////row = dataSet.Tables[0].NewRow();
                ////row["ID"] = "4";
                ////row["ParentID"] = "1";
                ////row["Text"] = "Child 2";
                ////dataSet.Tables[0].Rows.Add(row);

                ////row = dataSet.Tables[0].NewRow();
                ////row["ID"] = "5";
                ////row["ParentID"] = "2";
                ////row["Text"] = "Child 3";
                ////dataSet.Tables[0].Rows.Add(row);